

angular.module('SJ-APP', ['angularFileUpload']).config(['$interpolateProvider', function ($interpolateProvider) {
    $interpolateProvider.startSymbol('@{');
    $interpolateProvider.endSymbol('}@');
}]).controller('contest_review_task_list_controller', ['$scope', '$http','FileUploader',function ($scope, $http, FileUploader) {




    //文件上传
    var uploader = $scope.uploader = new FileUploader({
        url: '/contests/contest/v2/review/task/upload_works_excel'
    });

    // FILTERS

    uploader.filters.push({
        name: 'customFilter',
        fn: function(item /*{File|FileLikeObject}*/, options) {
            return this.queue.length < 10;
        }
    });

    // CALLBACKS

    uploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/, filter, options) {
        console.info('onWhenAddingFileFailed', item, filter, options);
    };
    uploader.onAfterAddingFile = function(fileItem) {
        console.info('onAfterAddingFile', fileItem);
    };
    uploader.onAfterAddingAll = function(addedFileItems) {
        console.info('onAfterAddingAll', addedFileItems);
    };
    uploader.onBeforeUploadItem = function(item) {
        console.info('onBeforeUploadItem', item);
    };
    uploader.onProgressItem = function(fileItem, progress) {
        console.info('onProgressItem', fileItem, progress);
    };
    uploader.onProgressAll = function(progress) {
        console.info('onProgressAll', progress);
    };
    uploader.onSuccessItem = function(fileItem, response, status, headers) {
        console.info('onSuccessItem', fileItem, response, status, headers);
    };
    uploader.onErrorItem = function(fileItem, response, status, headers) {
        console.info('onErrorItem', fileItem, response, status, headers);
    };
    uploader.onCancelItem = function(fileItem, response, status, headers) {
        console.info('onCancelItem', fileItem, response, status, headers);
    };
    uploader.onCompleteItem = function(fileItem, response, status, headers) {
        console.info('onCompleteItem', fileItem, response, status, headers);
        if(response.status == 200){
            $scope.result.filePath = response.data.path;
        }
    };
    uploader.onCompleteAll = function() {
        console.info('onCompleteAll');
    };

    console.info('uploader', uploader);

























    //测试上传
    $scope.onFileSelect = function(files){
        alert(88);
    };


    $scope.show = function(){
        console.log($scope.result.userId);
    };


    $scope.sjApp = sjApp;

    //初始化时间选择控件
    $('.form_datetime').datetimepicker({
        initialDate : new Date(new Date().setSeconds(0)),
        language:  'zh-CN',
        weekStart: 1,
        todayBtn:  1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        //minView : 2,
        forceParse: 0,
        showMeridian: 0
    });


    //初始化评审任务数据
    var taskObj = {
        "createdTime":'',
        "updateTime":'',
        "state":'',
        "sourceCount":'',
        "endTime":'',
        "sourceIds":"",
        "id":"",
        "startTime":'',
        "title":"",
        "effect":true,
        "description":"",
        "reviewCount":'',
        "userId":'',
        "userName":"",
        "tagetList":[
            {
                "createdTime":'',
                "description":"",
                "finalCount":'',
                "finalIds":"",
                "id":"",
                "reviewTaskId":"",
                "tagetCount":'',
                "title":"",
                "updateTime":''
            }
        ],
        "selectType":0,
        filePath:''
    };

    var review_target = {
        tagetCount: '',
        title: "",
        "reviewTaskId":""
    };

    //当前任务 评审结果使
    $scope._curTask = '';
    $scope.isEdit = false;
    $scope.curTaskTargets = '';
    $scope.searchParamsObj= {};
    $scope.searchParamsObj.tagetId = '';
    $scope._orignalTask = '';


    //大赛详情
    $scope._contestDetailLink = '';
    $scope.contestDetail = '';
    var contestId = $.getUrlParam('contestId');
    //先获取大赛的基本信息
    var postDataD = {
        contestId : contestId
    };
    $http.post('/contests/contest/detail', postDataD)
        .success(function(data){
            if(data.status == '200'){
                var cur_contest = data;
                if(typeof(cur_contest) != 'undefined'){
                    if (cur_contest instanceof Array && cur_contest.length) {
                        $scope.contestDetail = cur_contest[0];
                    }else{
                        cur_contest.data.title = sjApp.htmldecode(cur_contest.data.title);
                        $scope.contestDetail = cur_contest.data;

                        $scope._contestDetailLink = host + '/page/contestv/views/index?id=' + cur_contest.data.id + '&r='+ cur_contest.data.refer + '&p=index' ;
                    }
                }

            }else if(data.status == '302'){
                layer.msg('您没有该权限');
            }else{
                layer.msg('服务器错误', {
                    icon: 1,
                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                }, function(){
                    //do something

                });
            }
        });

    $scope.newTaskData = function(){
        var taskTem = angular.copy(taskObj);
        taskTem.userId = taskTem.userId.split(',');
        taskTem.effect = !taskTem.effect;
        $scope.result = taskTem;


        $scope._curTask = '';
        $scope.isEdit = false;
        $scope.curTaskTargets = '';
        $scope.searchParamsObj= {};
        $scope.startTime = $scope.time_change($scope.startTime);
        $scope.endTime = $scope.time_change($scope.endTime);


        $('.upload-action-works-review-lxx').val('');
        $scope.uploader.queue = [];
        console.log($scope.result);
        console.log($scope.uploader);
    };
    $scope.addReviewTask = function(){
        $scope.newTaskData();
        $("#modalLabel-task-window").html('添加评审任务');
        $("#myModal-task-window").modal('show');
    };


    //添加评委
    $scope.add_rater = function(index){
        $scope.result.userId.splice(index+1,0,'');
    };
    //删除评委
    $scope.remove_rater = function(index){
        $scope.result.userId.splice(index,1);
    };

    //添加评审目标
    $scope.add_review_target = function(index){
        $scope.result.tagetList.splice(index+1, 0, angular.copy(review_target))
    };
    //删除评审任务
    $scope.remove_review_target = function(index){
        $scope.result.tagetList.splice(index,1);
    };

    $scope.time_change = function(time_val,numFlag){
        if(!time_val){
            return '';
        }
        var curDate = new Date(time_val);
        if(numFlag){
            return curDate.getTime();
        }else{
            return curDate.pattern("yyyy-MM-dd HH:mm");
        }
    };

    //编辑任务
    $scope.editTask = function(rowData){
        var taskTem = angular.copy(rowData);
        $("#modalLabel-task-window").html('编辑评审任务');
        $scope.isEdit = true;
        taskTem.userId = taskTem.userId.split(',');
        taskTem.effect = !taskTem.effect;
        taskTem.startTime = $scope.time_change(taskTem.startTime);
        taskTem.endTime = $scope.time_change(taskTem.endTime);

        $scope.$apply(function(){
            $scope.result = taskTem;
            $scope._orignalTask = angular.copy(taskTem);
        });
        $("#myModal-task-window").modal('show');
    };

    //新增/保存 任务
    $scope.saveReviewTask = function(){
        var postData = angular.copy($scope.result);
        console.log(postData.sourceIds.length);
        if(!postData.title){
            layer.alert('评审任务标题不能为空',{icon: 5});
            return false;
        }
        //TODO
        if(postData.selectType == 1 && !postData.filePath && (!$scope.isEdit || ($scope.isEdit &&
            $scope._orignalTask.selectType == 0))){
            layer.alert('待选作品为自定义时，需要上传对应的Excel文件',{icon: 5});
            return false;
        }

        if($("#myModal-task-window .btn-submit").hasClass('disabled')){
            return;
        }

        postData.userId = postData.userId.join(',');
        postData.effect = !postData.effect;
        postData.startTime = $scope.time_change(postData.startTime,true);
        postData.endTime = $scope.time_change(postData.endTime,true);


        var sendParams = {
            contestId: $.getUrlParam('contestId'),
            jsonData:  JSON.stringify(postData)
        };
        if($scope.isEdit && $scope._curTask){
            sendParams.taskId = $scope._curTask.id;
        }

        $.ajax({
            url:'/contests/contest/review/addTask',
            dataType:'json',
            method:"POST",
            data: sendParams,
            success:function(data){
                layer.closeAll('loading');
                if(data.status == '200'){
                    layer.alert('发布任务成功', {icon: 1},function(){
                        layer.closeAll('dialog');
                        $("#myModal-task-window .btn-submit").removeClass('disabled');
                        $("#myModal-task-window").modal('hide');
                        $("#dataTable").dataTable().fnDraw();
                    });
                }else if(data.status == '500'){
                    layer.alert('服务器错误，请确认信息填写是否有误');
                    $("#myModal-task-window .btn-submit").removeClass('disabled');
                }
                console.log(data);
            },
            beforeSend:function(){
                layer.load(0, {shade: false});
                $("#myModal-task-window .btn-submit").addClass('disabled');
            }
        });
    };


    //删除 task
    $scope.deleteTask = function(taskId){
        layer.confirm('确认删除该任务?', {icon: 3, title:'提示'}, function(index){
            $.ajax({
                url:'/contests/contest/review/deleteTask',
                dataType:'json',
                method:"POST",
                data: {
                    taskId: taskId
                },
                success:function(data){
                    layer.closeAll('loading');
                    if(data.status == '200'){
                        layer.alert('删除任务成功', {icon: 1},function(){
                            layer.closeAll('dialog');
                            $("#dataTable").dataTable().fnDraw();
                        });
                    }else if(data.status == '500'){
                        layer.alert('服务器错误，请稍后再试');
                    }
                    console.log(data);
                },
                beforeSend:function(){
                    layer.load(0, {shade: false});
                }
            });

            layer.close(index);
        });
    };

    //查看评审结果
    $scope.showResult = function(){
        $("#myModal-review-result-set").modal('show');
        if($.fn.dataTable.isDataTable('#dataTable-review-list')){
            $('#dataTable-review-list').dataTable().fnDraw();
        }else{
            $scope.initReviewResult();
        }
    };
    //刷新评审结果列表
    $scope.getReviewResult = function(){
        $('#dataTable-review-list').dataTable().fnDraw();
    };
    //导出评审结果列表
    $scope.exportReviewResult = function(){
        var exportUrl = '/contests/contest/review_task_result/export_excel?tagetId=' + $scope.searchParamsObj.id
            + "&tagetName="+ $scope.searchParamsObj.title
            + "&contestName="+ $scope.contestDetail.title
            + "&raterName="+ $scope._curTask.userName
            + "&page=1&size=-1";

        // {"name":"page","value":pageIndex},
        // {"name":"size","value":pageSize},
        // {"name":"tagetId","value":$scope.searchParamsObj.tagetId}
        $("#export-iframe").append("<iframe id='ifr' style='display:none;' src='"+ exportUrl + "'></iframe>");
    };

    //导出当前任务的待评审作品
    $scope.exportReviewWorklist = function(){
        console.log($scope._curTask);
        var exportUrl = '/contests/contest/review_task/export_work_list_excel?taskId=' + $scope._curTask.id
            + "&contestName="+ $scope.contestDetail.title
            + "&page=1&size=16";

        $("#export-iframe-worklist").append("<iframe id='ifr' style='display:none;' src='"+ exportUrl + "'></iframe>");

    };

    //初始化 评审结果列表
    $scope.initReviewResult = function(){

        $('#dataTable-review-list').dataTable({
            language: {
                "sProcessing": "处理中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "",//(由 _MAX_ 项结果过滤)
                "sInfoPostFix": "",
                "sSearch": "搜索:",
                "sUrl": "",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                },
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            },
            /*aoColumns:[ //设定各列宽度
             {"sWidth": "10%"},
             {"sWidth": "30%"},
             {"sWidth": "30%"},
             {"sWidth": "30%"}
             ],
             <th>大赛名称</th>
             <th>创建时间</th>
             <th>作品数量</th>
             <!--<th>参赛人数</th>-->
             <th>当前状态</th>
             <th>推荐</th>
             <th>权重</th>
             <th>管理</th>*/
            columns: [
                {title: '作品ID', data: 'id', "mRender" : function(data, type, full) {
                    var rHtml = '<a href="' + host + '/community/photo-details/' + full.id + '" target="_blank">' + data + '</a>';
                    return rHtml;
                }},
                {
                    title : '评委昵称',
                    data : 'userInfo',
                    "mRender" : function(data, type, full) {
                        return $scope._curTask.userName;
                    }
                },
                {title: '作品标题',data: 'title', "mRender" : function(data, type, full) {
                    return data?data:'--';
                }},
                {
                    title: '作者', data: 'userInfo', "mRender" : function(data, type, full) {
                    return data.userName?data.userName:'--';
                }},
                {
                    title: '用户ID', data: 'id', "mRender" : function(data, type, full) {
                    return data?data:'--';
                }},
                {title: '作品缩略图',data: 'url', "mRender" : function(data, type, full) {
                    if (data) {
                        var rHtml = '<a href="'+ host + '/community/photo-details/' + full.id + '" target="_blank">' + '<img style="height:100px;width:auto;" src="' + data.p1 + '"/></a>';
                        return rHtml;
                    }

                }},
                {title: '评审结果',data: 'id', "mRender" : function(data, type, full) {
                    return $scope.searchParamsObj.title ? $scope.searchParamsObj.title:'--';
                }}
            ],
            "bSort": false,
            "bProcessing": true, //加载数据时显示正在加载信息
            "bServerSide": true, //指定从服务器端获取数据
            "bFilter": false, //不使用过滤功能
            "bLengthChange": false, //用户不可改变每页显示数量
            "iDisplayLength": 16, //每页显示10条数据
            "sAjaxSource": '/contests/contest/v2/get/review/tagetList',
            "fnServerParams" : function (aoData) {
                var pageSize = aoData[4].value;
                var pageIndex = aoData[3].value/pageSize+1;

                aoData.push(
                    {"name":"page","value":pageIndex},
                    {"name":"size","value":pageSize},
                    {"name":"tagetId","value": $scope.searchParamsObj.id}, //,$scope._curTask.id
                    {"name":"tagetName","value":$scope.searchParamsObj.title}
                );

            },
            "fnServerData": function( sSource, aoData, fnCallback ) {
                var pageSize = aoData[4].value;
                var pageIndex = aoData[3].value/pageSize+1;

                $.ajax({
                    type: "post",
                    dataType:'json', //接受数据格式
                    cache:false,
                    data : aoData,
                    //data : {
                    //    page : pageIndex,
                    //    size : pageSize,
                    //    contestId : $.getUrlParam('contestId')
                    //},
                    url: sSource,
                    success: function(data, textStatus){
                        var r = {
                            iTotalRecords : 50,
                            iTotalDisplayRecords : 50,
                            aaData : []
                        };
                        if(data instanceof Array){
                            r.aaData = data;
                        }else{
                            // var t ={};
                            // t.aaData = data.data;
                            // t.iTotalDisplayRecords = data.iTotalRecords;
                            // r =t;
                            data.aaData = data.data;
                            data.iTotalDisplayRecords = data.searchHitsTotal;
                            r = data;
                        }
                        fnCallback(r);
                    },
                    error: function(){
                        //请求出错处理
                        // alert("error");
                    }
                });

            }, //获取数据的处理函数
            "sPaginationType": "full_numbers", //翻页界面类型
            "headerClickable":false,
            "sortable":false/*,
             data: cur_result ||[{
             title: 'aa',
             createdTime: 'bb',
             itemCount: 3,
             state: 1,
             recommendation: 3,
             rating: 0
             }]*/
//         "sDom": "<'pull-right'l>t<'row'<'col-lg-6'f><'col-lg-6'p>>",
//         "sPaginationType": "bootstrap",
//         "oLanguage": {
//             "sLengthMenu": "Show _MENU_ entries"
//         }
        });
    };




    $('#dataTable').dataTable({
        language: {
            "sProcessing": "处理中...",
            "sLengthMenu": "显示 _MENU_ 项结果",
            "sZeroRecords": "没有匹配结果",
            "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
            "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
            "sInfoFiltered": "",//(由 _MAX_ 项结果过滤)
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            },
            "oAria": {
                "sSortAscending": ": 以升序排列此列",
                "sSortDescending": ": 以降序排列此列"
            }
        },
        /*aoColumns:[ //设定各列宽度
         {"sWidth": "10%"},
         {"sWidth": "30%"},
         {"sWidth": "30%"},
         {"sWidth": "30%"}
         ],
         <th>大赛名称</th>
         <th>创建时间</th>
         <th>作品数量</th>
         <!--<th>参赛人数</th>-->
         <th>当前状态</th>
         <th>推荐</th>
         <th>权重</th>
         <th>管理</th>*/
        columns: [
            {title: '评审任务名称', data: 'title', "mRender" : function(data, type, full) {
                return data?data:'--';
            }},
            {
                title : '评委昵称',
                data : 'userName',
                "mRender" : function(data, type, full) {
                    return data?data:'--';
                }
            },
            {title: '评委/用户ID',data: 'userId', "mRender" : function(data, type, full) {
                return data?data:'--';
            }},
            {
                title: '评审启动日期', data: 'startTime', "mRender" : function(data, type, full) {
                return data?new Date(data).pattern('yyyy-MM-dd HH:mm:ss'):'--';
            }},
            {
                title: '评审结束日期', data: 'endTime', "mRender" : function(data, type, full) {
                return data?new Date(data).pattern('yyyy-MM-dd HH:mm:ss'):'--';
            }},
            {title: '评审目标(入选数/目标数)',data: 'tagetList', "mRender" : function(data, type, full) {
                var rHtml = '';
                if(data && data instanceof Array && data.length > 0){
                    var color = '#000';
                    data.map(function(item, index){
                        rHtml = rHtml + '<span style="color: ' + color +'">'+ item.title + '（' + item.finalCount + '/' + item.tagetCount + '）' +  '</span><br/>';
                        if(color == '#000'){
                            color = 'grey';
                        }else {
                            color = '#000';
                        }
                    });
                }else {
                    rHtml = '--';
                }
                return rHtml;

            }},
            {title: '发布状态',data: 'effect', "mRender" : function(data, type, full) {
                return data?'已发布':'暂不发布';
            }},
            {title: '状态',data: 'state', "mRender" : function(data, type, full) {
                return data?'已提交':'未提交';
            }},
            {title: '结果',data: 'effect', createdCell: function (td, cellData, rowData, row, col) {
                $(td).html('');
                var editeEl = $('<a class="btn btn-metis-6 btn-xs btn-line">评审结果</a>');
                $(td).append(editeEl);

                editeEl.click(function(){
                    $scope.$apply(function(){
                        $scope._curTask = rowData;
                        $scope.searchParamsObj = ($scope._curTask.tagetList.length>0)?$scope._curTask.tagetList[0]:''
                    });
                    $scope.showResult();
                });
            }
            },
            {title: '评阅进度',data: 'reviewCount', "mRender" : function(data, type, full) {
                return data?(data + '/' + full.sourceCount): (0 + '/' + full.sourceCount);
            }},
            {
                title : '操作',
                "data": null,
                "orderable": false,
                //"defaultContent": "<button>删除</button>&nbsp;<button>编辑</button>",
                createdCell: function (td, cellData, rowData, row, col) {
                    $(td).html('');
                    var editeEl = $('<a class="btn btn-metis-6 btn-xs btn-line">编辑</a>');
                    var deleteEl = $('<a class="btn btn-danger btn-xs btn-line">删除</a>&nbsp;&nbsp;');




                    $(td).append(editeEl);
                    $(td).append('&nbsp;&nbsp');
                    $(td).append(deleteEl);



                    editeEl.click(function(){
                        $scope._curTask = rowData;
                        $scope.editTask(rowData);
                    });
                    deleteEl.click(function(){
                        $scope.deleteTask(rowData.id);
                    });
                    //detailEl.click(function(){
                    //    $scope.showDetail(rowData.id);
                    //});
                    //quitEl.click(function(){
                    //    $scope.quitContest(rowData.id, $.getUrlParam('contestId'));
                    //});
                    //prizeEditEl.click(function(){
                    //    $scope.$apply(function(){
                    //        $scope.resource_prizeTable = rowData;
                    //        $scope.objAddPrize.resourceId = rowData.id;
                    //    })
                    //
                    //    $scope.setPrizeShowWin(rowData.id, $.getUrlParam('contestId'));
                    //});

                }
            }
        ],
        "bSort": false,
        "bProcessing": true, //加载数据时显示正在加载信息
        "bServerSide": true, //指定从服务器端获取数据
        "bFilter": false, //不使用过滤功能
        "bLengthChange": false, //用户不可改变每页显示数量
        "iDisplayLength": 16, //每页显示10条数据
        "sAjaxSource": '/contests/contest/v2/get/review_task_list',
        "fnServerParams" : function (aoData) {
            var pageSize = aoData[4].value;
            var pageIndex = aoData[3].value/pageSize+1;
            aoData.push(
                {"name":"page","value":pageIndex},
                {"name":"size","value":pageSize},
                {"name":"contestId","value":$.getUrlParam('contestId')?$.getUrlParam('contestId'):''}
            );

        },
        "fnServerData": function( sSource, aoData, fnCallback ) {
            var pageSize = aoData[4].value;
            var pageIndex = aoData[3].value/pageSize+1;

            $.ajax({
                type: "post",
                dataType:'json', //接受数据格式
                cache:false,
                data : aoData,
                //data : {
                //    page : pageIndex,
                //    size : pageSize,
                //    contestId : $.getUrlParam('contestId')
                //},
                url: sSource,
                success: function(data, textStatus){
                    var r = {
                        iTotalRecords : 50,
                        iTotalDisplayRecords : 50,
                        aaData : []
                    };
                    if(data instanceof Array){
                        r.aaData = data;
                    }else{
                        // var t ={};
                        // t.aaData = data.data;
                        // t.iTotalDisplayRecords = data.iTotalRecords;
                        // r =t;
                        data.aaData = data.data;
                        data.iTotalDisplayRecords = data.searchHitsTotal;
                        r = data;
                    }
                    fnCallback(r);
                },
                error: function(){
                    //请求出错处理
                    // alert("error");
                }
            });

        }, //获取数据的处理函数
        "sPaginationType": "full_numbers", //翻页界面类型
        "headerClickable":false,
        "sortable":false/*,
         data: cur_result ||[{
         title: 'aa',
         createdTime: 'bb',
         itemCount: 3,
         state: 1,
         recommendation: 3,
         rating: 0
         }]*/
//         "sDom": "<'pull-right'l>t<'row'<'col-lg-6'f><'col-lg-6'p>>",
//         "sPaginationType": "bootstrap",
//         "oLanguage": {
//             "sLengthMenu": "Show _MENU_ entries"
//         }
    });


}]);